package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.pojo.SoundTimes;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(version = "1.0.0")
public class SoundApiImpl implements SoundApi {


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public String saveSound(Sound sound) {

        if (sound.getUserId()==null){
            return null;
        }
        sound.setId(ObjectId.get());
        sound.setCreated(System.currentTimeMillis());

        mongoTemplate.save(sound);

        return sound.getId().toHexString();
    }

    @Override
    public Boolean saveTimes(SoundTimes soundTimes) {
        if (soundTimes.getUserId()==null){
            return false;
        }

        soundTimes.setId(ObjectId.get());

        SoundTimes times = mongoTemplate.save(soundTimes);

        if (times != null){

            return true;
        }

        return false;
    }

    //修改
    @Override
    public void updateTimes(Long userId,Integer times) {


        mongoTemplate.updateFirst(Query.query(Criteria.where("userId").is(userId)),
                Update.update("remainingTimes",times),
                SoundTimes.class);

    }

    @Override
    public void updatedate(Long userId,Long date) {


        mongoTemplate.updateFirst(Query.query(Criteria.where("userId").is(userId)),
                Update.update("date",date),
                SoundTimes.class);

    }
    //删除
    @Override
    public void removeSound(ObjectId id) {

        Query query  = Query.query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,Sound.class);
    }


    @Override
    public SoundTimes queryTimes(Long userId) {

        Query query= Query.query(Criteria.where("userId").is(userId));
        SoundTimes soundTimes = mongoTemplate.findOne(query,SoundTimes.class);

        return soundTimes;
    }


    /**
     * 查询语音列表
     *
     * @param
     * @return
     */
    @Override
    public List<Sound> querySoundList() {

        Query query= new Query();
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);

        return soundList;
    }
}
